<template>
  <div>
    <DynamicTable :data-request="loadTableData" :columns="columns" showIndex>
      <template #toolbar>
        <a-button type="primary" @click="openAddDrawer({})"> <PlusOutlined />新增 </a-button>
      </template></DynamicTable
    >
  </div>
</template>

<script lang="tsx" setup>
  import { h, onMounted, reactive, ref, unref } from 'vue';
  import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
  import {
    baseColumns,
    type TableListItem,
    type TableColumnItem,
  } from '@/views/organization/roles/columns';
  import { useRoleSchema } from '@/views/organization/roles/formSchema';
  import {
    getRoleListPage,
    deleteRole,
    createRole,
    editRole,
    roleDepart,
    roleMenus,
    roleUsers,
    getAllDepts,
  } from '@/api/organization/roles/roles';
  import { getMenuList } from '@/api/system/menu';
  import { useTable } from '@/components/core/dynamic-table';
  import { useFormDrawer } from '@/hooks/useDrawer/useFormDrawer';
  import { useDrawer } from '@/hooks/useDrawer/useDrawer';
  import RoleAuth from './roleAuth.vue';
  import { formatMenu2Tree, formatDept2Tree } from '@/core/permission/utils';
  import { cloneDeep } from 'lodash-es';
  import { message } from 'ant-design-vue';

  defineOptions({
    name: 'RoleList',
  });

  const editDrawerBindValue = reactive({
    roleData: {},
    depts: [],
    menus: [],
    users: [],
    deptsAll: [],
    menusAll: [],
    menuKeysAll: [],
    deptsKeysAll: [],
  });

  const [DynamicTable, dynamicTableInstance] = useTable({
    size: 'small',
    rowKey: 'id',
    bordered: true,
  });
  // 加载表格数据
  const loadTableData = async (params) => {
    const data = await getRoleListPage({
      ...params,
      pageNum:params.page,
      pageSize: params.limit,
    });

    return {
      list: data.rows || [],
      pagination: {
        total: data.total,
        size: params.limit,
        page: params.page,
      },
    };
  };

  const [showDrawer] = useFormDrawer();
  const [DrawerRender] = useDrawer();

  const editFormRef = ref<any>(null);

  // 自定义组件抽屉
  const handleEditRole = async (record) => {
    editDrawerBindValue.roleData = { ...record };
    handleRoleAuthAll(record.roleId);
    DrawerRender.show({
      title: '编辑角色',
      width: 700,
      // 是否显示右上角确定取消
      defaultExtra: true,
      destroyOnClose: true,
      content: () => {
        return <RoleAuth ref={editFormRef} defaultData={unref(editDrawerBindValue)}></RoleAuth>;
      },
      // 确定方法执行
      onOk: async (values) => {
        const res = await editFormRef.value?.handleSubmit();
        if (!res) return;
        const result = await editRole(res);
        console.log(result);
        if (result.error == '200') {
          message.success('修改成功');
          dynamicTableInstance.reload();
        }
      },
    });
  };
  // Form 抽屉达开
  const openAddDrawer = async (record: Partial<TableListItem>) => {
    const [formRef] = await showDrawer({
      drawerProps: {
        title: `新增角色`,
        width: 700,
        defaultExtra: true,
        onFinish: async (values) => {
          await (record.roleId ? editRole : createRole)(values);
          dynamicTableInstance.reload();
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: useRoleSchema(),
      },
    });

    formRef?.setFieldsValue({
      ...record,
    });
  };
  // 删除角色
  const delRowConfirm = async (id: any) => {
    await deleteRole({
      roleId: id,
    });
    dynamicTableInstance.reload();
  };

  // 获取角色对应的用户 部门 菜单
  const handleRoleAuthAll = async (id) => {
    const [users, depts, menus] = await Promise.all([
      roleUsers({roleId:id, pageNum: 1, pageSize: 5 }),
      roleDepart({ id }),
      roleMenus({ id }),
    ]);
    editDrawerBindValue.users = users?.rows ?? [];
    editDrawerBindValue.depts =
      depts && depts.result ? depts?.result.map((item) => item.dept_Id) : [];
    editDrawerBindValue.menus =
      menus && menus.result ? menus?.result.map((item) => item.menuId) : [];
  };

  // 获取所有数据
  const handleDefaultData = async () => {
    const [depts, menus] = await Promise.all([
      getAllDepts({ name: '', companyid: '', page: 0, pagesize: 0 }),
      getMenuList({ menuName: '' }),
    ]);
    console.log(depts,"depts1111");
    editDrawerBindValue.deptsAll =
      depts && depts.rows ? formatDept2Tree(cloneDeep(depts.rows), '0') : [];
    editDrawerBindValue.deptsKeysAll =
      depts && depts.result ? depts.result.list.map((item) => item.dept_Id) : [];
    editDrawerBindValue.menusAll =
      menus && menus.result ? formatMenu2Tree(cloneDeep(menus.result), '0') : [];
    editDrawerBindValue.menuKeysAll =
      menus && menus.result ? menus.result.map((item) => item.menuId) : [];
    
      console.log(editDrawerBindValue,"editDrawerBindValue1111");
  };

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '操作',
      width: 220,
      dataIndex: 'ACTION',
      hideInSearch: true,
      align: 'center',
      actions: ({ record }) => [
        {
          label: '编辑',
          icon: h(EditOutlined),
          onClick: () => handleEditRole(record),
        },
        {
          label: '删除',
          danger: true,
          icon: h(DeleteOutlined),
          popConfirm: {
            title: '你确定要删除吗？',
            onConfirm: () => delRowConfirm(record.roleId),
          },
        },
      ],
    },
  ];

  onMounted(() => {
    handleDefaultData();
  });
</script>
